package com.blocks.mq.producer.reader.impl;

import com.blocks.mq.producer.reader.Reader;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

public class ExcelReader implements Reader {
//    @Override


    @Override
    public String reader(String path) throws IOException {
        String str = "";
        try (InputStream inp = new FileInputStream(path)) {
            Workbook wb = WorkbookFactory.create(inp);
            for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
                Sheet st = wb.getSheetAt(sheetIndex);
                Iterator<Row> iterator = st.iterator();
                while (iterator.hasNext()) {
                    Row row = iterator.next();
                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();

                        switch (cell.getCellTypeEnum()) {
                            case STRING:
                                str += (cell.getRichStringCellValue() + " ");
                                break;
                            case NUMERIC:
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    str += (cell.getDateCellValue() + " ");
                                } else {
                                    str += (cell.getNumericCellValue() + " ");
                                }
                                break;
                            case BOOLEAN:
                                str += (cell.getBooleanCellValue() + " ");
                                break;
                            case FORMULA:
                                str += (cell.getCellFormula() + " ");
                                break;
                            case BLANK:
                                System.out.println();
                                break;
                        }
                    }
                    str += "\r\n";
                }

            }

        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }
        return str;
    }
}
